package ext.acae2.util;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.URLEncoder;
import java.sql.Timestamp;

import wt.method.RemoteAccess;
import wt.util.WTProperties;


public class ReportUtil implements RemoteAccess, Serializable {

    private static final String CLASSNAME = ReportUtil.class.getName();
    public static boolean VERBOSE = false;

    static {
        try {
            WTProperties wtProperties = WTProperties.getLocalProperties();
            VERBOSE = "true".equalsIgnoreCase(wtProperties
                    .getProperty(CLASSNAME + ".verbose"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void downloadFile(String fileName,
                                    HttpServletResponse response) throws IOException {

        int index = fileName.lastIndexOf(File.separator);
        String displayName = fileName.substring(index + 1);
        displayName = URLEncoder.encode(displayName, "UTF-8");
        OutputStream os = response.getOutputStream();

        response.setContentType("application/x-msdownload; charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + displayName + "\"");

        System.out.println("Test fileName = " + fileName);
        File temp = new File(fileName);
        InputStream input = new FileInputStream(temp);

        byte[] buff = new byte[512];

        int len;
        while ((len = input.read(buff)) != -1) {
            os.write(buff, 0, len);
        }

        input.close();

        response.setStatus(HttpServletResponse.SC_OK);
        response.flushBuffer();

        os.flush();

    }

    /**
     * change String date to Timestamp date
     *
     * @param strTime string time
     * @return ts
     */
    public static Timestamp changeStartTime(String strTime) {
        Timestamp changedTime;
        String TimeStyle;
        if (strTime != null && !strTime.equals("")) {
            TimeStyle = strTime.concat(" 00:00:00");
        } else {
            java.text.SimpleDateFormat f = new java.text.SimpleDateFormat(
                    "yyyy/MM/dd");
            TimeStyle = f.format(new java.util.Date()).concat(" 00:00:00");
        }
        changedTime = Timestamp.valueOf(TimeStyle.replaceAll("/", "-"));
        return changedTime;
    }
}